﻿#include "AF_Animation.h"

namespace AF
{
	UINT Animation::m_nID = 0;
	UINT Animation::GetID()
	{
		return m_nID++;
	}

	Animation::Animation() :
		ATTRIB(HostGraphics)(NULL),
		ATTRIB(State)(AS_STOP),
		ATTRIB(Loop)(false),
		m_pResponse(NULL),
		m_pTimer(NULL),
		m_ttInterval(0),
		m_isExactTimer(false)
	{
		static char _szAnimationName[20];
		_MEMSET(_szAnimationName, 0, sizeof(_szAnimationName));
		_SPRINTF(_szAnimationName, "A_%d", GetID());
		ATTRIB(AnimationName) = _szAnimationName;
	}

	Animation::~Animation()
	{
		if(m_pTimer != NULL)
			AF_DELETE(m_pTimer);
	}

	void Animation::SetAnimationName(_STRING strAnimationName)
	{
		if(ATTRIB(AnimationName).substr(0, 2) == "A_")
			ATTRIB(AnimationName) = strAnimationName;
	}

	void Animation::Play(Bundle* pParam)
	{
		AF_CHECK(ATTRIB(State) != AS_PLAY);

		if(OnPlay(pParam))
		{
			if(m_pTimer == NULL)
			{
				m_pTimer = AF_NEW(Timer);
				m_pTimer->SetRunClass(this);
				if(m_isExactTimer)
					m_pTimer->Exact();
			}
			m_pTimer->SetInterval(m_ttInterval);

			if(m_pTimer->Start())
			{
				ATTRIB(State) = AS_PLAY;

				if(m_pResponse != NULL)
				{
					m_pResponse->OnAnimationResponse(this, AS_PLAY);
				}
			}
		}
	}

	void Animation::Pause()
	{
		AF_CHECK(ATTRIB(State) == AS_PLAY);

		if(OnPause())
		{
			AF_ASSERT(m_pTimer != NULL);

			m_pTimer->Stop();
			ATTRIB(State) = AS_PAUSE;

			if(m_pResponse != NULL)
			{
				m_pResponse->OnAnimationResponse(this, AS_PAUSE);
			}
		}
	}

	bool Animation::Stop()
	{
		AF_CHECK_R(ATTRIB(State) != AS_STOP, false);

		if(OnStop())
		{
			AF_ASSERT_R(m_pTimer != NULL, false);

			m_pTimer->Stop();
			ATTRIB(State) = AS_STOP;

			if(m_pResponse != NULL)
			{
				m_pResponse->OnAnimationResponse(this, AS_STOP);
			}

			return true;
		}

		return false;
	}

	void Animation::ExactTimer()
	{
		m_isExactTimer = true;
	}

	void Animation::OnRun(RunBase* pRunBase)
	{
		if(pRunBase == m_pTimer)
		{
//			ATTRIB(State) = AF_AS_RUN;
				
			bool isContinue = OnUpdate();
			if(m_pResponse != NULL)
			{
				m_pResponse->OnAnimationResponse(this, AS_RUN);
			}

			if(!isContinue)
			{
				Stop();
			}
		}
	}

	void Animation::SetResponse(AnimationResponse* pResponse)
	{
		AF_CHECK(pResponse != NULL);

		m_pResponse = pResponse;
	}

	void Animation::SetInterval(TimeTicks ttInterval)
	{
		m_ttInterval = ttInterval;
	}

}
